package com.hmall.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hmall.search.mapper.SearchMapper;
import com.hmall.search.pojo.Item;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author sjqn
 */
@Component
@Slf4j
public class MyTask {
    @Autowired
    private SearchMapper searchMapper;
    private static final String TOP_20_SOLD_ITEMS_KEY = "top_20_sold_items";
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 定时任务 每隔5秒触发一次
     */
    @Scheduled(cron = "0 0/2 * * * *")
    public void executeTask(){
        log.info("定时任务开始执行：{}", LocalDateTime.now());
        LambdaQueryWrapper<Item> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.orderByDesc(Item::getSold);
        lambdaQueryWrapper.last("LIMIT 20");
        List<Item> items = searchMapper.selectList(lambdaQueryWrapper);
        redisTemplate.delete(TOP_20_SOLD_ITEMS_KEY);

        redisTemplate.opsForList().rightPushAll(TOP_20_SOLD_ITEMS_KEY, items);
    }
}